package lumis.service.portalmanagement.reporttype;

import lumis.doui.processaction.ProcessActionHandler;
import lumis.doui.source.Source;
import lumis.portal.PortalException;
import lumis.portal.manager.ManagerFactoryInternal;
import lumis.portal.report.IReportManager;
import lumis.portal.report.ReportType;
import lumis.util.TextUtil;
import lumis.util.XmlUtil;

/**
*
* @version $Revision: 12710 $ $Date: 2011-03-18 17:00:16 -0300 (Fri, 18 Mar 2011) $
 * @since 4.1.0
*/
public class RegisterReportTypeProcessActionHandler extends ProcessActionHandler<Source>
{
	public void processAction() throws PortalException
	{
		String actionType = XmlUtil.readAttributeString("actionType", processActionNode);

		if (actionType == null)
			actionType = "registerExisting";

		if(actionType.equals("registerNew"))
		{
			registerNewReportType();
		}
		else if (actionType.equals("registerExisting"))
		{
			registerExistingReportTypes();
		}
		else if (actionType.equals("unregister"))
		{
			unregisterReportTypes();
		}
	}

	public void registerNewReportType() throws PortalException
	{
		String baseUrl = getParameter("baseUrl", String.class);
		ManagerFactoryInternal.getReportManager().register(baseUrl);
		
		addDefaultResponse();
	}

	public void registerExistingReportTypes() throws PortalException
	{
		String[] ids = (String [])getParameter("id");
		if(ids != null)
		{
			IReportManager reportManager = ManagerFactoryInternal.getReportManager();
			for (String id: ids)
			{
				try
				{
					ReportType reportType = reportManager.getReportType(id);
					reportManager.register(reportType.getBaseUrl());
				}
				catch (PortalException e) 
				{
					throw new PortalException("STR_ERROR_REGISTERING_REPORT_TYPE;" + TextUtil.escapeLocalizationParameter(id) + ";" + TextUtil.escapeLocalizationParameter(e.getLocalizedMessage(sessionConfig.getLocale())), getResource());
				}
			}

			addResponseParameter(ProcessActionHandler.RESPONSE_TYPE_MESSAGE, localize("STR_REPORT_TYPE_REGISTERED_SUCCESSFULLY"));
		}
		addDefaultResponse();
	}

	public void unregisterReportTypes() throws PortalException
	{
		String[] ids = (String [])getParameter("id");
		if(ids != null)
		{
			IReportManager reportManager = ManagerFactoryInternal.getReportManager();
			for (String id: ids)
			{
				ReportType reportType = reportManager.getReportType(id);
				reportManager.unregister(reportType);
			}
			
			addResponseParameter(ProcessActionHandler.RESPONSE_TYPE_MESSAGE, localize("STR_REPORT_TYPE_UNREGISTERED_SUCCESSFULLY"));
		}
		
		addDefaultResponse();
	}
}
